package com.zsd.android.dblib.db;

import android.database.sqlite.SQLiteDatabase;

import com.zsd.android.dblib.enums.PrivateDatabaseEnums;

public class SubBaseDaoFactory extends BaseDaoFactory {

    private static volatile SubBaseDaoFactory instance;
    private SQLiteDatabase subSQLiteDatabase;

    private SubBaseDaoFactory() {}

    public static SubBaseDaoFactory getInstance() {
        SubBaseDaoFactory factory = instance;
        if (factory == null) {
            synchronized (SubBaseDaoFactory.class) {
                if (factory == null) {
                    factory = new SubBaseDaoFactory();
                    instance = factory;
                }
            }
        }
        return factory;
    }

    @Override
    public <T extends BaseDao, M> T getBaseDao(Class<T> daoClass, Class<M> entityClass) {
        String databasePath = PrivateDatabaseEnums.database.getValue();
        BaseDao baseDao = map.get(databasePath);
        if (baseDao != null) {
            return (T) baseDao;
        }
        subSQLiteDatabase = SQLiteDatabase.openOrCreateDatabase(databasePath, null);
        try {
            baseDao = daoClass.newInstance();
            baseDao.init(subSQLiteDatabase, entityClass);
            map.put(databasePath, baseDao);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return (T) baseDao;
    }
}
